﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HIWSystem.Common;
using HIWSystem.Models;
using System;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace HIWSystem.ViewModel
{
    public class AddBindStationViewModel : ViewModelBase
    {
        #region 属性

        private ObservableCollection<PartNumberEntity> pns;

        /// <summary>
        /// 机种集合
        /// </summary>
        public ObservableCollection<PartNumberEntity> PNs
        {
            get { return pns; }
            set { pns = value; this.RaisePropertyChanged(() => PNs); }
        }

        private ObservableCollection<RoutingEntity> flows;

        //流程集合
        public ObservableCollection<RoutingEntity> Flows
        {
            get { return flows; }
            set { flows = value; this.RaisePropertyChanged(() => Flows); }
        }

        private ObservableCollection<string> stations;

        //站位
        public ObservableCollection<string> Stations
        {
            get { return stations; }
            set { stations = value; this.RaisePropertyChanged(() => Stations); }
        }

        private ObservableCollection<string> bindStations;

        public ObservableCollection<string> BindStations
        {
            get { return bindStations; }
            set { bindStations = value; this.RaisePropertyChanged(() => BindStations); }
        }

        private RoutingEntity selectedFlow;

        public RoutingEntity SelectedFlow
        {
            get { return selectedFlow; }
            set { selectedFlow = value; this.RaisePropertyChanged(() => SelectedFlow); }
        }
        private ObservableCollection<BindingStationEntity> bindingStations;
        //绑定站位集合
        public ObservableCollection<BindingStationEntity> BindingStations
        {
            get { return bindingStations; }
            set { bindingStations = value; this.RaisePropertyChanged(() => BindingStations); }
        }

        #endregion 属性

        #region 命令

        private RelayCommand loadedCmd;

        public RelayCommand LoadedCmd
        {
            get
            {
                loadedCmd = loadedCmd ?? new RelayCommand(LoadedPage);
                return loadedCmd;
            }
            set { loadedCmd = value; }
        }

        private RelayCommand<PartNumberEntity> comboPNSelectionChangedCmd;

        public RelayCommand<PartNumberEntity> ComboPNSelectionChangedCmd
        {
            get
            {
                comboPNSelectionChangedCmd = comboPNSelectionChangedCmd ??
                    new RelayCommand<PartNumberEntity>(ComboPNSelectionChangedHandler);
                return comboPNSelectionChangedCmd;
            }
            set { comboPNSelectionChangedCmd = value; }
        }

        private RelayCommand<RoutingEntity> comboFlowSelectionChangedCmd;

        public RelayCommand<RoutingEntity> ComboFlowSelectionChangedCmd
        {
            get
            {
                comboFlowSelectionChangedCmd = comboFlowSelectionChangedCmd ??
                    new RelayCommand<RoutingEntity>(ComboFlowSelectionChangedHandler);
                return comboFlowSelectionChangedCmd;
            }
            set { comboFlowSelectionChangedCmd = value; }
        }

        private RelayCommand<string> lstStationMouseDoubleClick;

        public RelayCommand<string> LstStationMouseDoubleClick
        {
            get
            {
                lstStationMouseDoubleClick = lstStationMouseDoubleClick ??
                    new RelayCommand<string>(LstStationMouseDoubleClickHandler);
                return lstStationMouseDoubleClick;
            }
            set { lstStationMouseDoubleClick = value; }
        }

        private RelayCommand<string> lstBindStationMouseDoubleClick;

        public RelayCommand<string> LstBindStationMouseDoubleClick
        {
            get
            {
                lstBindStationMouseDoubleClick = lstBindStationMouseDoubleClick ??
                    new RelayCommand<string>(BindStationMouseDoubleClickHandler);
                return lstBindStationMouseDoubleClick;
            }
            set { lstBindStationMouseDoubleClick = value; }
        }

        private RelayCommand addCmd;

        public RelayCommand AddCmd
        {
            get
            {
                addCmd = addCmd ?? new RelayCommand(Add);
                return addCmd;
            }
            set { addCmd = value; }
        }
        private RelayCommand searchCmd;

        public RelayCommand SearchCmd
        {
            get {
                searchCmd = searchCmd ?? new RelayCommand(Search);
                return searchCmd; }
            set { searchCmd = value; }
        }
        private RelayCommand<BindingStationEntity> deleteBindingStationCmd;

        public RelayCommand<BindingStationEntity> DeleteBindingStationCmd
        {
            get {
                deleteBindingStationCmd = deleteBindingStationCmd ??
                    new RelayCommand<BindingStationEntity>(Delete);
                return deleteBindingStationCmd; }
            set { deleteBindingStationCmd = value; }
        }

        #endregion 命令

        #region 方法

        //页面加载
        private void LoadedPage()
        {
            _ = FillPNsToComboBoxAsync();
        }

        //添加捆绑站位信息
        private void Add()
        {
            string retMsg = string.Empty;
            if (BindStations == null || BindStations.Count <= 0)
            {
                MessageBox.Show("绑定站位列表是空的，请添加站位信息.", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            };

            string strStations = string.Join("|", BindStations.ToArray());
            retMsg = BusinessProcess.AddBindingStation(SelectedFlow?.Flow, strStations);

            if (retMsg.Split('|')[0] == "OK")
            {
                MessageBox.Show("添加成功!", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show("添加失败" + retMsg.Split('|')[1].ToString(), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        //查询系统中绑定的站位信息
        private void Search()
        {
            if ((SelectedFlow?.Flow??"")=="")
            {
                MessageBox.Show("流程不能为空!", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            string retMsg = string.Empty;//数据库返回的信息
            DataTable dtBindingStations = new DataTable();//绑定站位的基础信息
            retMsg= BusinessProcess.SearchBindingStation(SelectedFlow.Flow, out dtBindingStations, false);
            if (retMsg.Split('|')[0] == "OK")
            {
                BindingStations = new ObservableCollection<BindingStationEntity>();
                for (int i = 0; i < dtBindingStations.Rows.Count; i++)
                {
                    var entity = new BindingStationEntity
                    {
                        Id=Convert.ToInt32(dtBindingStations.Rows[i]["Id"].ToString()),
                        Flow = dtBindingStations.Rows[i]["Flow"].ToString() ?? "",
                        ArrayStation = dtBindingStations.Rows[i]["ArrayStation"].ToString() ?? "",
                        IsDelete = dtBindingStations.Rows[i]["IsDelete"].ToString() ?? ""
                    };
                    BindingStations.Add(entity);
                }
            }
            else
            {
                MessageBox.Show(string.Format("查询错误【{0}】",retMsg.Split('|')[1]), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        //删除绑定的站位
        private void Delete(BindingStationEntity obj)
        {
            string retMsg = string.Empty;//返回的状态信息
            string[] arrayMsg = new string[2];
            if (obj != null)
            {
                retMsg = BusinessProcess.EmployeeIsHaveModuleAuthority("AF");
                arrayMsg = retMsg.Split('|');
                //Y表示有权限
                if (arrayMsg[0] == "Y")
                {
                    //确定用户是否要删除，防止误删
                    MessageBoxResult boxResult = MessageBox.Show(string.Format("确定要删除这个流程【{0}】的绑定站位吗？", obj.Flow), "软件温馨提示!", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (boxResult == MessageBoxResult.Yes)
                    {
                        if (BusinessProcess.DeleteBindingStation(obj.Id).Split('|')[0]=="OK")
                        {
                            BindingStations.Remove(obj);
                        }
                        else
                        {
                            MessageBox.Show("删除失败", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show(arrayMsg[1], "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }

        //机种下拉列表框改变事件
        private void ComboPNSelectionChangedHandler(PartNumberEntity obj)
        {
            if (obj != null)
            {
                var dtFlow = new DataTable();
                dtFlow = BusinessProcess.GetFlowsByPN(obj.PN);
                Flows = new ObservableCollection<RoutingEntity>();
                for (int i = 0; i < dtFlow.Rows.Count; i++)
                {
                    RoutingEntity routingEntity = new RoutingEntity { Flow = dtFlow.Rows[i]["Flow"].ToString() };
                    Flows.Add(routingEntity);
                }
            }
        }

        //流程下拉框改变事件
        private void ComboFlowSelectionChangedHandler(RoutingEntity obj)
        {
            if (obj != null)
            {
                Stations = new ObservableCollection<string>();
                var dtRouting = new DataTable();
                BusinessProcess.GetRoutingByFlow(obj.Flow, out dtRouting);
                for (int i = 0; i < dtRouting.Rows.Count; i++)
                {
                    Stations.Add(dtRouting.Rows[i]["Station"].ToString());
                }
            }
        }

        //流程站位列表鼠标双击事件
        private void LstStationMouseDoubleClickHandler(string obj)
        {
            if (obj != null)
            {
                BindStations = BindStations ?? new ObservableCollection<string>();
                if (!BindStations.Contains(obj))
                {
                    BindStations.Add(obj);
                }
            }
        }

        //绑定站位鼠标双击事件
        private void BindStationMouseDoubleClickHandler(string obj)
        {
            if (obj != null)
            {
                BindStations.Remove(obj);
            }
        }

        //填充机种信息到下拉列表框
        private async Task FillPNsToComboBoxAsync()
        {
            await Task.Run(() =>
            {
                DataTable dtPNs = new DataTable();
                dtPNs = BusinessProcess.GetPNs(EnumPNType.All);
                PNs = new ObservableCollection<PartNumberEntity>();
                for (int i = 0; i < dtPNs.Rows.Count; i++)
                {
                    PNs.Add(new PartNumberEntity
                    {
                        PN = dtPNs.Rows[i]["PartNumber"].ToString()
                    });
                }
            });
        }

        #endregion 方法
    }
}